// eslint-disable-next-line no-unused-vars
import { AxiosInstance } from 'axios';
import { observable, action } from 'mobx';
import {
    requestFn,
    postBlogComment,
    getBlogContent,
    getBlogComments,
} from '../lib/httpReq';

interface InitialSatate{
    blogInfo: {};
    comments: UserComment[];
    nextAndPrev: {};
}

const initialState: InitialSatate = {
    blogInfo: {},
    comments: [],
    nextAndPrev: {},
};

export class BlogContent {
    constructor({ blogInfo, comments, nextAndPrev } = initialState) {
        this.blogInfo = blogInfo;
        this.comments = comments;
        this.nextAndPrev = nextAndPrev;
    }

    @observable blogInfo: {};

    @observable comments: UserComment[];

    @observable nextAndPrev: {};

    @action.bound
    setComments = (comments: UserComment[]) => {
        this.comments = comments;
    };

    @action.bound
    setBlogInfo = (blogInfo: BlogContentData) => {
        this.blogInfo = blogInfo;
    };

    @action.bound
    setNextAndPrev = (nextAndPrev: NextAndPrevData) => {
        this.nextAndPrev = nextAndPrev;
    };

    @action.bound
    postComment = (
        commentInfo: BlogUserComment,
        success: (data: UserComment) => void,
        fail: (msg: FailRes) => void,
    ) => {
        requestFn(postBlogComment, [commentInfo], (data) => {
            this.setComments([data, ...this.comments]);
            success(data);
        }, (msg) => {
            fail(msg);
        });
    };

    @action.bound
    getBlogComments = (blogId: string, axiosInstance?: AxiosInstance) => {
        requestFn(getBlogComments, [blogId, axiosInstance], (data) => {
            this.setComments(data);
        });
    };

    @action.bound
    getBlogContent = (blogId: string, axiosInstance?: AxiosInstance, isReqComment = false) => {
        requestFn(getBlogContent, [blogId, axiosInstance], ({ result }) => {
            this.setBlogInfo(result.result);
            this.setNextAndPrev(result.nextAndPrev);
            if (isReqComment) {
                // 请求用户评论信息
                this.getBlogComments(result.result._id, axiosInstance);
            }
        });
    };
}

export const BLOG_CONTENT = 'blogContent';
